<?php
if (!defined("APP_PATH")) {
    define('APP_PATH', __DIR__ . '/../application/');
    // 加载框架引导文件
    require __DIR__ . '/../thinkphp/start.php';
}

use think\Db;
use think\Exception;
use think\Log;
use fast\Http;

set_time_limit(0);
get_order_result();


function get_order_result()
{
    $debug = config("app_debug");

    if (php_sapi_name() != 'cli' && !$debug) {
        // echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }

    echo '开始执行的时间：' . date('Y-m-d H:i:s') . "\r\n";

    $today = date("Ymd");
    $redis = rds();
    $bkey = 'get_order_result_day' . $today;

    $op = $redis->set($bkey, 1, ['NX', 'EX' => 86500]);
    if (!$op) {
        echo "已结算";
        die;
    }

    $user = \db('user')->field('id,credit1,credit2,credit6')->select();
    $u_credit9 = "";
    $u_credit6 = "";
    foreach ($user as $k => $v) {
        $uid = $v['id'];
        $value = round($v['credit2'] * 0.03, 4);
        if(round($v['credit1'],4) == 0) {
            continue;
        }

        if ($value + $v['credit6'] > $v['credit1']) {
            $value = $v['credit1'] - $v['credit6'];
        }

        $u_credit9 .= " when id={$uid} then credit9+{$value} "; //充值的
        $u_credit6 .= " when id={$uid} then credit6+{$value} "; //可提现
    }

    $prefix = config('database.prefix');
    $u_update = "";

    if ($u_credit9) {
        $u_update .= ",credit9=(case {$u_credit9} else credit9 end)";
    }

    if ($u_credit6) {
        $u_update .= ",credit6=(case {$u_credit6} else credit6 end)";
    }


    db::startTrans();
    try {
        if ($u_update) \db()->execute("UPDATE {$prefix}user SET " . trim($u_update, ','));
        db::commit();
    } catch (\Exception $e) {
        db::rollback();
        Log::error($e->getMessage());
        echo $e->getFile() . "(" . $e->getLine() . ")" . $e->getMessage();
        echo '执行失败：' . date('Y-m-d H:i:s') . "\r\n";
    }
    echo "\r\n" . '结束执行的时间：' . date('Y-m-d H:i:s') . "\r\n";
}


